var express = require('express');
var router = express.Router();
const {
    Course,
    Category,
    User,
    Chapter
} = require('../../models');
const {
    Op
} = require('sequelize');
const { success, error, notFound, formatPagination } = require('../../utils/response');
const { filterBody, getPaginationParams } = require('../../utils/filter');

// 获取课程查询配置
const getCourseQueryOptions = (query = {}) => {
    const { currentPage, pageSize, offset } = getPaginationParams(query);
    
    const options = {
        attributes: { exclude: ['userId', 'categoryId'] },
        include: [
            {
                model: Category,
                as: 'category',
                attributes: ['id', 'name']
            },
            {
                model: User,
                as: 'user',
                attributes: ['id', 'username']
            }
        ],
        order: [['id', 'DESC']]
    };

    // 如果需要分页
    if (currentPage && pageSize) {
        options.limit = pageSize;
        options.offset = offset;
    }

    // 构建查询条件
    const where = {};
    
    if (query.name) {
        where.name = {
            [Op.like]: `%${query.name}%`
        };
    }

    if (query.categoryId) {
        where.categoryId = query.categoryId;
    }

    if (query.recommended !== undefined) {
        where.recommended = query.recommended === 'true';
    }

    if (query.introductory !== undefined) {
        where.introductory = query.introductory === 'true';
    }

    if (Object.keys(where).length > 0) {
        options.where = where;
    }

    return options;
};

/* GET home page. */
// 获取课程列表
/**
 * @api {get} /admin/courses 获取课程列表
 * @apiGroup Courses
 * @apiVersion 1.0.0
 * @apiDescription 获取课程列表
 * @apiPermission 后台管理员
 * 
 */
router.get('/', async function (req, res, next) {
    try {
        const { currentPage, pageSize } = getPaginationParams(req.query);
        const queryOptions = getCourseQueryOptions(req.query);
        
        const {
            rows,
            count
        } = await Course.findAndCountAll(queryOptions);
        
        res.json(success(formatPagination(rows, count, currentPage, pageSize), '查询成功'));
    } catch (err) {
        console.error('课程查询失败:', err);
        res.json(error('查询失败', 500, err.message));
    }
});

// 查询课程详情
/**
 * @api {get} /admin/courses/:id 查询课程详情
 * @apiGroup Courses
 * @apiVersion 1.0.0
 */
router.get('/:id', async function (req, res, next) {
    try {
        const { id } = req.params;
        const queryOptions = getCourseQueryOptions();
        const course = await Course.findByPk(id, queryOptions);
        
        if (!course) {
            return res.status(404).json(notFound('课程'));
        }
        res.json(success(course, '查询成功'));
    } catch (err) {
        res.json(error('查询失败', 500, err.message));
    }
});

// 创建课程
/**
 * @api {post} /admin/courses/save 创建课程
 * @apiGroup Courses
 * @apiVersion 1.0.0
 */
router.post('/save', async function (req, res, next) {
    try {
        const body = filterBody(req.body, 'Course');
        const course = await Course.create(body);
        res.status(201).json(success(course, '创建成功', 201));
    } catch (err) {
        if (err.name === 'SequelizeValidationError') {
            const errors = err.errors.map(e => e.message);
            return res.status(400).json(error('创建失败', 400, errors));
        }
        res.json(error('创建失败'));
    }
});

//删除课程
/**
 * @api {delete} /admin/courses/:id 删除课程
 * @apiGroup Courses
 * @apiVersion 1.0.0
 */
router.delete('/:id', async function (req, res, next) {
    try {
        const {
            id
        } = req.params;
        const course = await Course.findByPk(id);
        if (!course) {
            return res.status(404).json(notFound('课程'));
        }
        const count = await Chapter.count({
            where: {
                courseId: id
            }
        });
        if (count > 0) {
            throw new Error('该课程下有章节，不能删除');
        }
        await course.destroy();
        res.json(success(null, '删除成功', 200));
    } catch (err) {
        res.json(error('删除失败', 500, err.message));
    }
});

// 更新课程
/**
 * @api {post} /admin/courses/update 更新课程
 * @apiGroup Courses
 * @apiVersion 1.0.0
 * 
 */
router.post('/update', async function (req, res, next) {
    try {
        const {
            id
        } = req.body;
        const course = await Course.findByPk(id);
        if (!course) {
            return res.status(404).json(notFound('课程'));
        }
        const updateData = filterBody(req.body, 'Course');
        await course.update(updateData);
        res.json(success(course, '更新成功'));
    } catch (err) {
        if (err.name === 'SequelizeValidationError') {
            const errors = err.errors.map(e => e.message);
            return res.status(400).json(error('更新失败', 400, errors));
        }
        res.json(error('更新失败'));
    }
});
module.exports = router;